﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CommonLibrary.Common;
using ServiceApplication.Service.Car;
using OAclient.Models;
using CommonLibrary.DataModel.Car;
using ServiceApplication.Service.Basic;
using OAclient.Common;
using System.Data;

namespace OAclient.Controllers
{
    public class CarController : Controller
    {
        //
        // GET: /Car/
        CarService cs = new CarService();
        BasicService bs = new BasicService();
        int PageSize = 15;
        //car-1
        public ActionResult CarList()
        {
            var dt = cs.CarQueryAll();
            ViewData["dt"] = dt;
            return View();
        }

        //car-2
        public ActionResult CarState(UserModel user)
        {
            List<SelectListItem> list_car = new List<SelectListItem>();
            var dt_car = cs.CarQueryAll();
            if (dt_car != null)
            {
                for (int i = 0; i < dt_car.Rows.Count; i++)
                {
                    list_car.Add(new SelectListItem
                    {
                        Selected = false,
                        Text = dt_car.Rows[i]["车辆名称"].ToString(),
                        Value = dt_car.Rows[i]["车辆编码"].ToString(),
                    });
                }
            }
            ViewData["list_car"] = list_car;
            //List<CarState> carstatelist = new List<CarState>();

            //var time = DateTime.Parse(query_time);
            //for (int i = 0; i < 7; i++)
            //{
            //    var tmp_time = time.AddDays(i);
            //    var stime = DateTime.Parse(DateUtil.getBeginTimeBySecond(tmp_time));//2012-12-10 00:00:00
            //    var etime = DateTime.Parse(DateUtil.getBeginTimeBySecond(tmp_time.AddDays(1)));//2012-12-11 00:00:00
            //    var dt = cs.ApplyQueryForCarState(stime.ToString("yyyy-MM-dd HH:mm:ss"), etime.ToString("yyyy-MM-dd HH:mm:ss"), query_carid);
            //    if (dt != null && dt.Rows.Count > 0)
            //    {
            //        for (int j = 0; j < dt.Rows.Count; j++)
            //        {
            //            var apply_stime = DateTime.Parse(dt.Rows[j]["开始时间"].ToString());
            //            var apply_etime = DateTime.Parse(dt.Rows[j]["结束时间"].ToString());
            //            if (apply_stime <= stime)
            //            {
            //                var shour = stime.Hour;
            //                if (apply_etime <= etime)
            //                {
            //                    var ehour = apply_etime.Hour;
            //                    carstatelist.Add(new CarState() { day = tmp_time.Day, name = dt.Rows[i]["申请人"].ToString(), s = shour, e = ehour });
            //                }
            //                else if (apply_etime > etime)
            //                {
            //                    var ehour = etime.Hour;
            //                    carstatelist.Add(new CarState() { day = tmp_time.Day, name = dt.Rows[i]["申请人"].ToString(), s = shour, e = ehour });
            //                }
            //            }
            //            else if (apply_stime > stime && apply_stime < etime)
            //            {
            //                var shour = apply_stime.Hour;
            //                if (apply_etime <= etime)
            //                {
            //                    var ehour = apply_etime.Hour;
            //                    carstatelist.Add(new CarState() { day = tmp_time.Day, name = dt.Rows[i]["申请人"].ToString(), s = shour, e = ehour });
            //                }
            //                else if (apply_etime > etime)
            //                {
            //                    var ehour = etime.Hour;
            //                    carstatelist.Add(new CarState() { day = tmp_time.Day, name = dt.Rows[i]["申请人"].ToString(), s = shour, e = ehour });
            //                }
            //            }
            //        }
            //    }
            //}
            return PartialView();
        }

        //apply-1
        public ActionResult ApplyAdd(UserModel user)
        {
            ViewData["sqr_id"] = user.user.user_id;

            List<SelectListItem> list_car = new List<SelectListItem>();
            var dt_car = cs.CarQueryAll();
            if (dt_car != null)
            {
                for (int i = 0; i < dt_car.Rows.Count; i++)
                {
                    list_car.Add(new SelectListItem
                    {
                        Selected = false,
                        Text = dt_car.Rows[i]["车辆名称"].ToString(),
                        Value = dt_car.Rows[i]["车辆编码"].ToString(),
                    });
                }
            }
            ViewData["list_car"] = list_car;

            return PartialView();
        }

        //apply-2
        public ActionResult ApplyListMy(UserModel user)
        {
            var dt = cs.ApplyQuery(new ApplyEntity() { sqr_id = user.user.user_id });
            ViewData["dt"] = dt;
            return PartialView();
        }

        //apply-4
        public ActionResult ApplyListAll(UserModel user, int? page)
        {
            if (page == null) page = 1;
            var query_sqr = Request.Form["query_sqr"] ?? Request.QueryString["query_sqr"];
            var query_czr = Request.Form["query_czr"] ?? Request.QueryString["query_czr"];
            var query_result = Request.Form["query_result"] ?? Request.QueryString["query_result"];
            var query_timetype = Request.Form["query_timetype"] ?? Request.QueryString["query_timetype"];
            var query_stime = Request.Form["query_stime"] ?? Request.QueryString["query_stime"];
            var query_etime = Request.Form["query_etime"] ?? Request.QueryString["query_etime"];

            ViewData["query_sqr"] = query_sqr;
            ViewData["query_czr"] = query_czr;
            ViewData["query_result"] = query_result;
            ViewData["query_timetype"] = query_timetype;
            ViewData["query_stime"] = query_stime;
            ViewData["query_etime"] = query_etime;

            var dt = cs.ApplyQueryByConditon(query_sqr, query_czr, query_result, query_timetype, query_stime, query_etime);

            var pageInfo = new PagingInfo
            {
                CurrentPage = page.Value,
                ItemsPerPage = PageSize,
                TotalItems = dt.Rows.Count
            };
            ViewData["pageInfo"] = pageInfo;
            if (dt.Rows.Count > 0)
                dt = dt.AsEnumerable().Skip((page.Value - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();
            ViewData["dt"] = dt;
            return PartialView();
        }

        //apply-3
        public ActionResult ApplyDetial(UserModel user, int apply_id)
        {
            var applyEntity = cs.ApplyQuery(apply_id);
            ViewData["apply_id"] = applyEntity.apply_id;
            ViewData["apply_stime"] = applyEntity.apply_stime;
            ViewData["apply_etime"] = applyEntity.apply_etime;
            ViewData["apply_time"] = applyEntity.apply_time;
            ViewData["apply_person"] = applyEntity.apply_person;

            ViewData["car_id"] = applyEntity.car_id;
            if (applyEntity.car_id > 0)
            {
                var carEntity = cs.CarQuery(applyEntity.car_id);
                ViewData["car_name"] = carEntity.car_name;
                ViewData["car_number"] = carEntity.car_number;
            }
            else
            {
                ViewData["car_name"] = "未分配";
                ViewData["car_number"] = "";
            }


            ViewData["sqr_id"] = applyEntity.sqr_id;
            if (applyEntity.sqr_id > 0)
            {
                var user_sqr = bs.QueryUser(applyEntity.sqr_id);
                ViewData["sqr_name"] = user_sqr.user_name;
            }

            ViewData["czr_id"] = applyEntity.car_id;
            if (applyEntity.czr_id > 0)
            {
                var user_czr = bs.QueryUser(applyEntity.czr_id);
                ViewData["czr_name"] = user_czr.user_name;
            }

            if (applyEntity.apply_result == 1)
                ViewData["apply_result"] = "同意";
            else if (applyEntity.apply_result == 0)
                ViewData["apply_result"] = "驳回";
            else if (applyEntity.apply_result == -1)
                ViewData["apply_result"] = "未处理";

            ViewData["apply_reply"] = applyEntity.apply_reply;
            return PartialView();
        }

        //apply-5
        public ActionResult ApplyDeal(UserModel user, int apply_id)
        {
            var applyEntity = cs.ApplyQuery(apply_id);
            ViewData["apply_id"] = applyEntity.apply_id;
            ViewData["apply_stime"] = applyEntity.apply_stime;
            ViewData["apply_etime"] = applyEntity.apply_etime;
            ViewData["apply_time"] = applyEntity.apply_time;
            ViewData["apply_person"] = applyEntity.apply_person;


            ViewData["car_id"] = applyEntity.car_id;
            if (applyEntity.car_id > 0)
            {
                var carEntity = cs.CarQuery(applyEntity.car_id);
                ViewData["car_name"] = carEntity.car_name;
                ViewData["car_number"] = carEntity.car_number;
            }
            List<SelectListItem> list_car = new List<SelectListItem>();
            list_car.Add(new SelectListItem
            {
                Selected = applyEntity.car_id == -1,
                Text = "不分配",
                Value = "-1",
            });
            var dt_car = cs.CarQueryAll();
            if (dt_car != null)
            {
                for (int i = 0; i < dt_car.Rows.Count; i++)
                {
                    list_car.Add(new SelectListItem
                    {
                        Selected = dt_car.Rows[i]["车辆编码"].ToString() == applyEntity.car_id.ToString(),
                        Text = dt_car.Rows[i]["车辆名称"].ToString(),
                        Value = dt_car.Rows[i]["车辆编码"].ToString(),
                    });
                }
            }
            ViewData["list_car"] = list_car;

            ViewData["sqr_id"] = applyEntity.sqr_id;
            if (applyEntity.sqr_id > 0)
            {
                var user_sqr = bs.QueryUser(applyEntity.sqr_id);
                ViewData["sqr_name"] = user_sqr.user_name;
            }


            if (applyEntity.czr_id > 0)//查看已处理
            {
                var user_czr = bs.QueryUser(applyEntity.czr_id);
                ViewData["czr_id"] = applyEntity.czr_id;
                ViewData["czr_name"] = user_czr.user_name;
            }
            else //未处理
            {
                ViewData["czr_id"] = user.user.user_id;
                ViewData["czr_name"] = user.user.user_name;
            }

            List<SelectListItem> list_result = new List<SelectListItem>();
            list_result.Add(new SelectListItem
            {
                Selected = applyEntity.apply_result == -1,
                Text = "未处理",
                Value = "-1",
            });
            list_result.Add(new SelectListItem
            {
                Selected = applyEntity.apply_result == 1,
                Text = "同意",
                Value = "1",
            });
            list_result.Add(new SelectListItem
            {
                Selected = applyEntity.apply_result == 0,
                Text = "驳回",
                Value = "0",
            });

            ViewData["list_result"] = list_result;

            ViewData["apply_reply"] = applyEntity.apply_reply;


            //检查是否有冲突项
            var dt_confict = cs.ApplyQueryConflict(apply_id);
            ViewData["dt_conflict"] = dt_confict;
            return PartialView();
        }




        #region 方法

        ///car

        public ActionResult DoCarAddOrUpdate(string car_id, string car_number, string car_name, string car_descn)
        {
            if (string.IsNullOrEmpty(car_name) || string.IsNullOrEmpty(car_number)) return Json(new ResTag(false), JsonRequestBehavior.AllowGet);
            if (car_descn == null) car_descn = string.Empty;
            int tmp_id;
            if (int.TryParse(car_id, out tmp_id))
            {
                CarEntity carEntity = new CarEntity()
                {
                    car_id = tmp_id,
                    car_name = car_name,
                    car_number = car_number,
                    car_descn = car_descn
                };
                cs.CarUpdate(carEntity);
            }
            else
            {
                CarEntity carEntity = new CarEntity()
                {
                    car_id = -1,
                    car_name = car_name,
                    car_number = car_number,
                    car_descn = car_descn
                };
                cs.CarAdd(carEntity);
            }

            return Json(new ResTag(true), JsonRequestBehavior.AllowGet);
        }

        public ActionResult DoCarDel(int car_id)
        {
            return Json(new ResTag(true), JsonRequestBehavior.AllowGet);
        }

        public ActionResult DoCarQuery(int car_id)
        {
            var carEntity = cs.CarQuery(car_id);
            return Json(carEntity, JsonRequestBehavior.AllowGet);
        }

        public ActionResult DoCarStateQuery(string query_time, int query_carid)
        {
            List<string[][]> resobj = new List<string[][]>();

            var time = DateTime.Parse(query_time);
            for (int i = 0; i < 7; i++)
            {
                var tmp_time = time.AddDays(i);
                var stime = DateTime.Parse(tmp_time.ToString("yyyy-MM-dd") + " 08:00:00");//2012-12-10 08:00:00
                var etime = DateTime.Parse(tmp_time.ToString("yyyy-MM-dd") + " 18:00:00");//2012-12-11 18:00:00
                var dt = cs.ApplyQueryForCarState(stime.ToString("yyyy-MM-dd HH:mm:ss"), etime.ToString("yyyy-MM-dd HH:mm:ss"), query_carid);
                List<CarStateModel> carstatelist = new List<CarStateModel>();
                //tmp_time.Day;

                if (dt != null && dt.Rows.Count > 0)
                {
                    //dt.Rows[i]["申请人"].ToString()
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        var apply_stime = DateTime.Parse(dt.Rows[j]["开始时间"].ToString());
                        var apply_etime = DateTime.Parse(dt.Rows[j]["结束时间"].ToString());
                        int shour = -1;
                        int ehour = -1;
                        if (apply_stime <= stime)
                        {
                            shour = stime.Hour;
                            if (apply_etime <= etime)
                            {
                                ehour = apply_etime.Hour;
                            }
                            else if (apply_etime > etime)
                            {
                                ehour = etime.Hour;
                            }
                        }
                        else if (apply_stime > stime && apply_stime < etime)
                        {
                            shour = apply_stime.Hour;
                            if (apply_etime <= etime)
                            {
                                ehour = apply_etime.Hour;
                            }
                            else if (apply_etime > etime)
                            {
                                ehour = etime.Hour;
                            }
                        }
                        if (shour >= 8 && ehour <= 18)
                        {
                            carstatelist.Add(new CarStateModel() { day = tmp_time.Day, name = dt.Rows[j]["申请人"].ToString(), shour = shour, ehour = ehour });
                        }
                    }
                }

                //如果当天有申请成功的记录，则填充空占据
                if (carstatelist.Count > 0)
                {
                    bool temp_flag = false;
                    int temp_length = 0;
                    int temp_shour = 8;
                    int temp_ehour = 18;
                    for (int j = 8; j < 18; j++)
                    {
                        if (carstatelist.Where(x => j >= x.shour && j < x.ehour).Count() > 0)//当前j小时已占
                        {
                            if (temp_flag && temp_length > 0 && temp_shour > 0)//当前小时已占 且 前一小时为空，则增加空占据
                            {
                                temp_ehour = j;
                                carstatelist.Add(new CarStateModel() { day = tmp_time.Day, name = "", shour = temp_shour, ehour = temp_ehour });
                            }

                            temp_flag = false;
                            temp_length = 0;
                            temp_shour = 8;
                            temp_ehour = 18;
                        }
                        else
                        {
                            if (temp_flag)
                            {
                                if (j == 17)
                                {
                                    temp_ehour = j;
                                    carstatelist.Add(new CarStateModel() { day = tmp_time.Day, name = "", shour = temp_shour, ehour = temp_ehour });
                                }
                                else
                                {
                                    temp_length++;
                                }
                            }
                            else
                            {
                                temp_flag = true;
                                temp_length = 1;
                                temp_shour = j;
                            }
                        }
                    }
                }
                else //如果当天没有已通过的申请记录
                {
                    carstatelist.Add(new CarStateModel() { day = tmp_time.Day, name = "", shour = 8, ehour = 18 });
                }
                carstatelist = carstatelist.OrderBy(x => x.shour).ToList();//时间排序
                string[][] s = new string[carstatelist.Count][];
                for (int j = 0; j < carstatelist.Count; j++)
                {
                    s[j] = new string[] { carstatelist[j].day.ToString(), carstatelist[j].name, carstatelist[j].shour.ToString(), carstatelist[j].ehour.ToString() };
                }

                resobj.Add(s);
            }


            return Json(resobj, JsonRequestBehavior.AllowGet);
        }


        ///apply

        public ActionResult DoApplyAdd(string apply_stime, string apply_etime, string apply_person, string sqr_id, string car_id)
        {
            ApplyEntity applyEntity = new ApplyEntity()
            {
                apply_id = -1,
                apply_stime = apply_stime,
                apply_etime = apply_etime,
                apply_time = DateUtil.getStandardTimeBySecond(),
                apply_person = apply_person,
                sqr_id = int.Parse(sqr_id),
                car_id = int.Parse(car_id),
                czr_id = -1,
                apply_result = -1,
                apply_reply = string.Empty,
                apply_cztime = string.Empty
            };
            cs.ApplyAdd(applyEntity);

            return Json(new ResTag(true), JsonRequestBehavior.AllowGet);
        }

        public ActionResult DoApplyUpdate(string apply_id, string car_id, string czr_id, string apply_result, string apply_reply)
        {
            var applyEntity = cs.ApplyQuery(int.Parse(apply_id));
            applyEntity.car_id = int.Parse(car_id);
            applyEntity.czr_id = int.Parse(czr_id);
            applyEntity.apply_result = int.Parse(apply_result);
            applyEntity.apply_reply = apply_reply;
            applyEntity.apply_cztime = DateUtil.getStandardTimeBySecond();
            cs.ApplyUpdate(applyEntity);
            return Json(new ResTag(true), JsonRequestBehavior.AllowGet);
        }

        public ActionResult DoApplyDel(string apply_id)
        {
            var applyEntity = cs.ApplyQuery(int.Parse(apply_id));
            if (applyEntity == null) return Json(new ResTag(false), JsonRequestBehavior.AllowGet);

            cs.ApplyDel(applyEntity.apply_id);
            return Json(new ResTag(true), JsonRequestBehavior.AllowGet);
        }



        #endregion


        #region 数据对象模型

        public class CarStateModel
        {
            public CarStateModel()
            {
            }
            public int day { set; get; }
            public string name { set; get; }
            public int shour { set; get; }
            public int ehour { set; get; }
        }

        #endregion

    }
}
